package com.example.demo.communication;

/**
 * ClassName: ThreadCommunicationDemo
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/07/31-15:48:00
 * Description:
 */
class TestCommunication {
    private static volatile Integer NUMBER = 0;

    /**
     * 加法: 只有为0的时候才加1
     */
    public synchronized void incr() throws InterruptedException {
        while (NUMBER != 0) {
            this.wait();
        }
        NUMBER++;
        System.out.println(Thread.currentThread().getName() + "线程加一成功," + "值为:" + NUMBER);
        notifyAll();
    }

    public synchronized void decr() throws InterruptedException {
        while (NUMBER == 0) {
            this.wait();
        }
        NUMBER--;
        System.out.println(Thread.currentThread().getName() + "线程减一成功," + "值为:" + NUMBER);
        notifyAll();
    }
}

public class ThreadCommunicationDemo {
    public static void main(String[] args) {
        TestCommunication comm = new TestCommunication();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    comm.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    comm.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();
    }
}
